Attribute VB_Name = "mdlCarriage"
Option Explicit


Public Function ApportionmentOfCarriage(ByVal Carriage As Double, ByVal StorageOutBillID As Long) As Long
Dim Sql As String
Dim Rst As ADODB.Recordset
Dim lrtn As Long
Dim OrderNum As Integer
Dim Qty    As Double
Dim TotalQty As Double
Dim SubCarriage As Double
Dim SubCarriageSum As Double
Dim CarriageBalance As Double
Dim RecordsAffected

    Sql = "Select isnull(sum(Quantity),0) as TotalQty from D_StorageOutDetail  where BillID=" & StorageOutBillID
    Set Rst = UI.Svr.cntMain.Execute(Sql, , adCmdText)
    TotalQty = Rst.Fields("TotalQty").Value
    If (TotalQty = 0) Then GoTo ExitEntry
    
    
    Sql = "Select OrderNum,Quantity from D_StorageOutDetail where BillID=" & StorageOutBillID
    Set Rst = UI.Svr.cntMain.Execute(Sql, , adCmdText)
    If (Rst.BOF And Rst.EOF) Then GoTo ExitEntry

      
    Do While Not Rst.EOF
        OrderNum = Rst.Fields("OrderNum").Value
        Qty = Rst.Fields("Quantity").Value
        SubCarriage = Round(Carriage * (Qty / TotalQty), 2)
        SubCarriageSum = SubCarriageSum + SubCarriage
        Sql = sprintf("Update D_StorageOutDetail set Carriage=%d where BillID=%d and OrderNum=%d", SubCarriage, StorageOutBillID, OrderNum)
        UI.Svr.cntMain.Execute Sql, RecordsAffected
        Debug.Assert RecordsAffected = 1
        Rst.MoveNext
    Loop
    
    If (SubCarriageSum <> Carriage) Then
        CarriageBalance = Carriage - SubCarriageSum
        Sql = sprintf("Update D_StorageOutDetail set Carriage=%d where BillID=%d and OrderNum=%d", SubCarriage + CarriageBalance, StorageOutBillID, OrderNum)
        UI.Svr.cntMain.Execute Sql, RecordsAffected
        Debug.Assert RecordsAffected = 1
    End If
    
    
    lrtn = gnSUCCESS
ExitEntry:
    ApportionmentOfCarriage = lrtn
    Exit Function
End Function
